package vip.fastgo.retroid.android.gamebox.view.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.Adapter

open abstract class BaseRvAdapter<T>(mContext: Context, list: ArrayList<T>): Adapter<BaseViewHolder>() {

    protected val mContext: Context
    val list: ArrayList<T>
    protected val inflater: LayoutInflater
    var onClickItemListener: OnClickItemListener? = null

    init {
        this.mContext = mContext
        this.list = list
        inflater = LayoutInflater.from(mContext)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val holder = createHolder(parent, viewType)
        holder.itemView.setOnClickListener {
            onClickItemListener?.onClickItem(this, it, holder.layoutPosition, -1)
        }
        return holder
    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        bindHolder(holder, position)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    /**
     * 添加数据
     */
    @SuppressLint("NotifyDataSetChanged")
    fun addAll(collections: Collection<out T>, isRefresh: Boolean = true) {
        if (collections.isEmpty()) {
            return
        }
        if (isRefresh) {
            this.list.clear()
            this.list.addAll(collections)
            notifyDataSetChanged()
        } else {
            val size = list.size
            list.addAll(collections)
            notifyItemRangeInserted(size, collections.size)
        }
    }

    abstract fun createHolder(parent: ViewGroup, viewType: Int) : BaseViewHolder

    abstract fun bindHolder(holder: BaseViewHolder, position: Int)

    interface OnClickItemListener {

        fun onClickItem(adapter: BaseRvAdapter<*>, view: View, position: Int, tag: Int)
    }
}